package com.probox.common.entity.service.platfom.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.*;
import java.util.concurrent.TimeUnit;

import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.constant.Constants;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.utils.DateUtils;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.entity.domain.wechat.vo.WechatTicketVo;
import com.probox.common.entity.service.platfom.IPlatformStoreService;
import com.probox.common.redis.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.probox.common.entity.mapper.platfom.PlatformMessageTemplateMapper;
import com.probox.common.entity.domain.platfom.PlatformMessageTemplate;
import com.probox.common.entity.service.platfom.IPlatformMessageTemplateService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 消息模板Service业务层处理
 *
 * @author usoft
 * @date 2021-07-21
 */
@Service
@Transactional
public class PlatformMessageTemplateServiceImpl extends ServiceImpl<PlatformMessageTemplateMapper, PlatformMessageTemplate> implements IPlatformMessageTemplateService {
    @Autowired
    private PlatformMessageTemplateMapper platformMessageTemplateMapper;

    @Autowired
    private IPlatformStoreService platformStoreService;

    @Autowired
    private RedisService redisService;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 查询消息模板
     *
     * @param templateUid 消息模板ID
     * @return 消息模板
     */
    @Override
    public PlatformMessageTemplate selectPlatformMessageTemplateById(Long templateUid) {
        return this.getById(templateUid);
    }

    /**
     * 查询消息模板列表
     *
     * @param platformMessageTemplate 消息模板
     * @return 消息模板
     */
    @Override
    public List<PlatformMessageTemplate> queryList(PlatformMessageTemplate platformMessageTemplate) {
        QueryWrapper<PlatformMessageTemplate> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(platformMessageTemplate.getTemplateUid())) && platformMessageTemplate.getTemplateUid() != null) {
            queryWrapper.eq("TEMPLATE_UID", platformMessageTemplate.getTemplateUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformMessageTemplate.getPlatformUid())) && platformMessageTemplate.getPlatformUid() != null) {
            queryWrapper.eq("PLATFORM_UID", platformMessageTemplate.getPlatformUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformMessageTemplate.getTemplateType())) && platformMessageTemplate.getTemplateType() != null) {
            queryWrapper.eq("TEMPLATE_TYPE", platformMessageTemplate.getTemplateType());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformMessageTemplate.getTemplateNo())) && platformMessageTemplate.getTemplateNo() != null) {
            queryWrapper.eq("TEMPLATE_NO", platformMessageTemplate.getTemplateNo());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformMessageTemplate.getTemplateTitle())) && platformMessageTemplate.getTemplateTitle() != null) {
            queryWrapper.like("TEMPLATE_TITLE", platformMessageTemplate.getTemplateTitle());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformMessageTemplate.getDataStatus())) && platformMessageTemplate.getDataStatus() != null) {
            queryWrapper.eq("DATA_STATUS", platformMessageTemplate.getDataStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformMessageTemplate.getCreateUser())) && platformMessageTemplate.getCreateUser() != null) {
            queryWrapper.eq("CREATE_USER", platformMessageTemplate.getCreateUser());
        }
        if (StringUtils.isNotEmpty(String.valueOf(platformMessageTemplate.getUpdateUser())) && platformMessageTemplate.getUpdateUser() != null) {
            queryWrapper.eq("UPDATE_USER", platformMessageTemplate.getUpdateUser());
        }
        queryWrapper.ne("DATA_STATUS",DataStatus.delete.getKey());

      List<PlatformMessageTemplate>  list=platformMessageTemplateMapper.selectList(queryWrapper);
        PlatformMessageTemplate vo=new PlatformMessageTemplate();
        Iterator<PlatformMessageTemplate> it=list.iterator();
        while (it.hasNext()){
            vo=it.next();
            vo.setStoreName(platformStoreService.getById(vo.getPlatformUid()).getStoreName());
        }


        return list;
    }

    /**
     * 新增消息模板
     *
     * @param platformMessageTemplate 消息模板
     * @return 结果
     */
    @Override
    public boolean insertPlatformMessageTemplate(PlatformMessageTemplate platformMessageTemplate) {

        platformMessageTemplate.setCreateUser(SecurityUtils.getUserId());

        platformMessageTemplate.setCreateTime(DateUtils.getNowDate());
        return this.save(platformMessageTemplate);

    }

    /**
     * 修改消息模板
     *
     * @param platformMessageTemplate 消息模板
     * @return 结果
     */
    @Override
    public boolean updatePlatformMessageTemplate(PlatformMessageTemplate platformMessageTemplate) {

        platformMessageTemplate.setUpdateUser(SecurityUtils.getUserId());

        platformMessageTemplate.setUpdateTime(DateUtils.getNowDate());
        return this.updateById(platformMessageTemplate);
    }

    /**
     * 批量删除消息模板
     *
     * @param templateUids 需要删除的消息模板ID
     * @return 结果
     */
    @Override
    public boolean deletePlatformMessageTemplateByIds(Long[] templateUids) {
        UpdateWrapper<PlatformMessageTemplate> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("TEMPLATE_UID", Arrays.asList(templateUids));
        updateWrapper.set("DATA_STATUS", DataStatus.delete.getKey());
        updateWrapper.set("UPDATE_User", SecurityUtils.getUserId());

        updateWrapper.set("UPDATE_TIME", DateUtil.date());
        return this.update(updateWrapper);
    }

    /**
     * 获取消息模板的模板id集合
     *
     * @return
     */
    @Override
    public List<String> getMessageIdList(String type) {
        List<String> list = new ArrayList<>();
        QueryWrapper<PlatformMessageTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        if (StringUtils.isEmpty(type)){
            type = "common";
        }
        queryWrapper.eq("TEMPLATE_TYPE", type);
        List<PlatformMessageTemplate> platformMessageTemplates = platformMessageTemplateMapper.selectList(queryWrapper);
        platformMessageTemplates.forEach(message -> {
            list.add(message.getTemplateNo());
        });
        return list;
    }

    private  String getToken(){
        String wechat_access_token_info = CachePrefix.WECHAT_ACCESS_TOKEN_INFO;
        String access_token = "";
        String data = redisService.getCacheObject(wechat_access_token_info);
        if (StringUtils.isEmpty(data)) {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ Constants.customer_app_id+"&secret="+Constants.customer_app_secret;
            String rst = HttpUtil.get(url);

            if (!StringUtils.isEmpty(rst)) {
                WechatTicketVo vo = JSONObject.parseObject(rst, WechatTicketVo.class);
                access_token = vo.getAccess_token();
                if (!StringUtils.isEmpty(access_token))
                    redisService.setCacheObject(wechat_access_token_info,rst,Long.parseLong(String.valueOf(vo.getExpires_in()-60)), TimeUnit.SECONDS);
            }
        }else {
            WechatTicketVo vo = JSONObject.parseObject(data, WechatTicketVo.class);
            access_token = vo.getAccess_token();
        }
        return access_token;
    }

    /**
     * B端用户token
     * @return
     */
    private  String getAdminToken(){
        String wechat_access_token_info = CachePrefix.ADMIN_WECHAT_ACCESS_TOKEN_INFO;
        String access_token = "";
        String data = redisService.getCacheObject(wechat_access_token_info);
        if (StringUtils.isEmpty(data)) {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ Constants.business_app_id+"&secret="+Constants.business_app_secret;
            String rst = HttpUtil.get(url);

            if (!StringUtils.isEmpty(rst)) {
                WechatTicketVo vo = JSONObject.parseObject(rst, WechatTicketVo.class);
                access_token = vo.getAccess_token();
                if (!StringUtils.isEmpty(access_token))
                    redisService.setCacheObject(wechat_access_token_info,rst,Long.parseLong(String.valueOf(vo.getExpires_in()-60)), TimeUnit.SECONDS);
            }
        }else {
            WechatTicketVo vo = JSONObject.parseObject(data, WechatTicketVo.class);
            access_token = vo.getAccess_token();
        }
        return access_token;
    }

    private  String getPublicCSToken(){
        String wechat_access_token_info = CachePrefix.PUBLIC_WECHAT_ACCESS_TOKEN_INFO;
        String access_token = "";
        String data = redisService.getCacheObject(wechat_access_token_info);
        if (StringUtils.isEmpty(data)) {

            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ Constants.gzh_app_id+"&secret="+Constants.gzh_app_secret;
            String rst = HttpUtil.get(url);

            if (!StringUtils.isEmpty(rst)) {
                WechatTicketVo vo = JSONObject.parseObject(rst, WechatTicketVo.class);
                access_token = vo.getAccess_token();
                if (!StringUtils.isEmpty(access_token))
                    redisService.setCacheObject(wechat_access_token_info,rst,5L, TimeUnit.MINUTES);
            }
        }else {
            WechatTicketVo vo = JSONObject.parseObject(data, WechatTicketVo.class);
            access_token = vo.getAccess_token();
        }
        return access_token;
    }

    /**
     * 通知客服
     * @param subscribeId
     * @param subscribeDate
     * @param item
     * @param custId
     * @param custName
     * @param csOpenId
     * @param csName
     * @param csStore
     * @return
     */
    public String noticeCS(Long subscribeId,String subscribeDate,String item,Long custId,String custName,String csOpenId,String csName,String csStore) {
        String url = message_url + getAdminToken();
        Map<String,Object> body = new HashMap<>();
        body.put("touser",csOpenId);

        //预约提醒
        body.put("template_id","e9w8vAnk_EQIlBzhmLCneYK_oekug15gGJEVrT3McDE");
        body.put("page","/pages/serviceDetail/serviceDetail?type=msgCard&subscribeId="+subscribeId+"&customerId="+custId);
        body.put("miniprogram_state","formal");
        body.put("lang","zh_CN");

        Map<String,Object> data = new HashMap<>();
        body.put("data",data);

        Map<String,String> name6 = new HashMap<>();
        name6.put("value",custName);
        data.put("name6",name6);

        Map<String,String> time2 = new HashMap<>();
        time2.put("value",subscribeDate);
        data.put("time2",time2);

        Map<String,String> thing7 = new HashMap<>();
        thing7.put("value",item);
        data.put("thing7",thing7);

        Map<String,String> name5 = new HashMap<>();
        name5.put("value",csName);
        data.put("name5",name5);

        Map<String,String> thing8 = new HashMap<>();
        thing8.put("value",csStore);
        data.put("thing8",thing8);

        String bodyStr = JSONObject.toJSONString(body);
        String rst = HttpUtil.post(url,bodyStr);
        logger.info("noticeCS===>{}",rst);
        return rst;
    }

    /**
     * 通知公众号
     * @param subscribeId
     * @param subscribeDate
     * @param item
     * @param custId
     * @param custName
     * @param csOpenId
     * @param csName
     * @param csStore
     * @return
     */
    public String noticePublicCS(Long subscribeId,String subscribeDate,String item,Long custId,String custName,String csOpenId,String csName,String csStore) {
        String url = uniform_send_url + getPublicCSToken();
        //String url = uniform_send_url+"73_I6k2KIJWpfa-9MR8QJK5ymb-KHBROlO3-vDUMWzzJJjZjtTFD1tKnM9d9GD30MunBJfiTQpcnSyCzIs07DMQl8tFI73g-Vre55b9Y3OGPpmq_PD9J8T5eZmzcAIMPGbAJADGX";
        Map<String,Object> body = new HashMap<>();
        body.put("touser",csOpenId);
        //body.put("appid","wx309ec160e62829a4");
        body.put("template_id","-lorNPe3cEHP9tGX2exh6poo4pLZQiK1FIu5DiNfFYM");
        body.put("url","http://weixin.qq.com/download");
        //Map<String,Object> template = new HashMap<>();
        //body.put("mp_template_msg",template);

        //预约提醒


        Map<String,String> mp = new HashMap<>();
        mp.put("appid","wx549c1cd8f6eac77e");
        mp.put("pagepath","/pages/serviceDetail/serviceDetail?type=msgCard&subscribeId="+subscribeId+"&customerId="+custId);
        body.put("miniprogram",mp);


        /*
        {
           "touser":"OPENID",
           "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
           "url":"http://weixin.qq.com/download",
           "miniprogram":{
             "appid":"xiaochengxuappid12345",
             "pagepath":"index?foo=bar"
           },
           "client_msg_id":"MSG_000001",
           "data":{

                   "keyword1":{
                       "value":"巧克力"
                   },
                   "keyword2": {
                       "value":"39.8元"
                   },
                   "keyword3": {
                       "value":"2014年9月22日"
                   }
           }
       }

        */
        Map<String,Object> data = new HashMap<>();
        body.put("data",data);

        Map<String,String> first = new HashMap<>();
        first.put("value","您有一个新的预约单！");
        data.put("first",first);

        Map<String,String> name6 = new HashMap<>();
        name6.put("value",custName);
        data.put("keyword1",name6);

        Map<String,String> time2 = new HashMap<>();
        time2.put("value",subscribeDate);
        data.put("keyword2",time2);

        Map<String,String> thing7 = new HashMap<>();
        thing7.put("value",item);
        data.put("keyword5",thing7);

        Map<String,String> name5 = new HashMap<>();
        name5.put("value",csName);
        data.put("keyword4",name5);

        Map<String,String> thing8 = new HashMap<>();
        thing8.put("value",csStore);
        data.put("keyword3",thing8);

        Map<String,String> remark = new HashMap<>();
        remark.put("value","请按时做好客户服务工作!");
        data.put("remark",remark);


        String bodyStr = JSONObject.toJSONString(body);
        String rst = HttpUtil.post(url,bodyStr);
        logger.info("noticePublicCS===>{}",rst);
        return rst;
    }


    /**
     * 取消服务通知
     * @param subscribeId
     * @param subscribeDate
     * @param item
     * @param custId
     * @param custName
     * @param csOpenId
     * @param csName
     * @param reason
     * @return
     */
    public String cancelNoticePublicCS(Long subscribeId,String subscribeDate,String item,Long custId,String custName,String csOpenId,String csName,String reason) {
        String url = uniform_send_url + getPublicCSToken();
        //String url = uniform_send_url+"73_I6k2KIJWpfa-9MR8QJK5ymb-KHBROlO3-vDUMWzzJJjZjtTFD1tKnM9d9GD30MunBJfiTQpcnSyCzIs07DMQl8tFI73g-Vre55b9Y3OGPpmq_PD9J8T5eZmzcAIMPGbAJADGX";
        Map<String,Object> body = new HashMap<>();
        body.put("touser",csOpenId);
        //body.put("appid","wx309ec160e62829a4");
        body.put("template_id","iFw86RzxmflPe3xrqUdCM6CEcWOhxff95iXg-_Jos5U");
        body.put("url","http://weixin.qq.com/download");
        //Map<String,Object> template = new HashMap<>();
        //body.put("mp_template_msg",template);

        //取消预约提醒
        Map<String,String> mp = new HashMap<>();
        mp.put("appid","wx549c1cd8f6eac77e");
        mp.put("pagepath","/pages/serviceDetail/serviceDetail?type=msgCard&subscribeId="+subscribeId+"&customerId="+custId);
        body.put("miniprogram",mp);

        Map<String,Object> data = new HashMap<>();
        body.put("data",data);

        Map<String,String> first = new HashMap<>();
        first.put("value",custName+"预约单取消提醒！");
        data.put("first",first);

        Map<String,String> time2 = new HashMap<>();
        time2.put("value",subscribeDate);
        data.put("keyword3",time2);

        Map<String,String> thing7 = new HashMap<>();
        thing7.put("value",item);
        data.put("keyword2",thing7);

        Map<String,String> name5 = new HashMap<>();
        name5.put("value",csName);
        data.put("keyword1",name5);

        Map<String,String> name4 = new HashMap<>();
        name4.put("value",reason);
        data.put("keyword4",name4);


        Map<String,String> remark = new HashMap<>();
        remark.put("value","请及时调整服务内容!");
        data.put("remark",remark);

        String bodyStr = JSONObject.toJSONString(body);
        String rst = HttpUtil.post(url,bodyStr);
        logger.info("cancel cancelNoticePublicCS===>{}",rst);
        return rst;
    }

    //发送消息模板
    private static final String message_url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";

    //private static final String uniform_send_url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=";
    private static final String uniform_send_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
    @Override
    public String sendMessage(String type,String openId,String para, Map<String,String> map) {
        String url = message_url + getToken();
        Map<String,Object> body = new HashMap<>();
        body.put("touser",openId);

        //预约提醒
        if (type.equals("subscribeTip")){
            body.put("template_id","AeUsOkBag6AZc1-TQy7e1sL4CLSbLLODecYUi6OUwKw");
            body.put("page","/thirdPages/preengageDetail/preengageDetail?type=1&"+para);
            body.put("miniprogram_state","formal");
            body.put("lang","zh_CN");

            Map<String,Object> data = new HashMap<>();
            body.put("data",data);

            Map<String,String> thing1 = new HashMap<>();
            thing1.put("value",map.get("title"));
            data.put("thing1",thing1);

            Map<String,String> time2 = new HashMap<>();
            time2.put("value",map.get("time"));
            data.put("time2",time2);

            Map<String,String> thing8 = new HashMap<>();
            thing8.put("value",map.get("store"));
            data.put("thing8",thing8);

            Map<String,String> phone_number12 = new HashMap<>();
            phone_number12.put("value",map.get("storePhone"));
            data.put("phone_number12",phone_number12);

            Map<String,String> thing4 = new HashMap<>();
            thing4.put("value",map.get("storeAddress"));
            data.put("thing4",thing4);
            String bodyStr = JSONObject.toJSONString(body);
            String rst = HttpUtil.post(url,bodyStr);
            logger.info("sendMessage===>{}",rst);
            return rst;

        }else if (type.equals("addTip")){
            //增补提醒
            body.put("template_id","bQ4OkGjXiywudGZfdCjxdNqu8a1fToF8umkpwlbXMIk");
            body.put("page","/thirdPages/preengageDetail/preengageDetail?type=1&"+para);
            body.put("miniprogram_state","formal");
            body.put("lang","zh_CN");

            Map<String,Object> data = new HashMap<>();
            body.put("data",data);

            Map<String,String> thing1 = new HashMap<>();
            thing1.put("value",map.get("title"));
            data.put("thing1",thing1);

            Map<String,String> time2 = new HashMap<>();
            time2.put("value",map.get("time"));
            data.put("time2",time2);

            Map<String,String> thing4 = new HashMap<>();
            thing4.put("value","美容师给您新增了服务项目，请您及时确认");
            data.put("thing4",thing4);

            String bodyStr = JSONObject.toJSONString(body);
            String rst = HttpUtil.post(url,bodyStr);
            logger.info("sendMessage===>{}",rst);
            return rst;
        }
        return "";
    }

}
